import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import Interfaces.IDataChannelListener;
import Interfaces.IDataHandler;
import Messages.MonitorDataMassage;


public class DataChannelListener extends Thread implements IDataChannelListener 
{
	private boolean m_isListening;
	private DatagramSocket m_socket;
	private IDataHandler m_dataHandler;
	
	public DataChannelListener(int port, IDataHandler dataHandler) throws SocketException
	{
		m_isListening = false;
		m_dataHandler = dataHandler;
		m_socket = new DatagramSocket(port);
	}

	public void startListening() 
	{
		m_isListening = true;
		start();
	}

	public void stopListening() 
	{
		m_isListening = false;
		m_socket.close();
	}
	
	@Override
	public void run()
	{
		while(m_isListening)
		{
			try 
			{
				System.out.println("Start data channel listening thread");
				// max message size
				byte[] buffer = new byte[1000];
			    DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
			    
				m_socket.receive(packet);
				
			    ByteArrayInputStream baos = new ByteArrayInputStream(buffer);
			    ObjectInputStream oos = new ObjectInputStream(baos);
				MonitorDataMassage data = (MonitorDataMassage)oos.readObject();
				System.out.println("Got data message");
				m_dataHandler.HandleData(packet.getAddress().getHostAddress(), 
									     data.Type, 
									     data.parameters, 
									     data.TimeStamp, 
									     data.Data);
			} 
			catch (IOException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			catch (ClassNotFoundException e) 
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
